from rest_framework import serializers  # 添加缺少的导入
from .models import Pet
from django.utils import timezone
from user.serializers import UserSerializer  # 导入用户序列化器

class PetSerializer(serializers.ModelSerializer):
    # 将owner字段序列化为只读字段，显示用户名
    owner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    owner_name = serializers.ReadOnlyField(source='owner.username')  # 添加只读字段显示主人用户名
    
    class Meta:
        model = Pet
        fields = ['id', 'owner', 'owner_name', 'name', 'age', 'sex', 'image', 'birth_date', 'breed', 'weight', 'height', 'create_time', 'update_time']
        read_only_fields = ['create_time', 'update_time', 'owner']  # owner设为只读，自动从当前登录用户获取
    
    def validate_age(self, value):
        """验证宠物年龄"""
        if value < 0:
            raise serializers.ValidationError("年龄不能为负数")
        return value
        
    def validate_weight(self, value):
        """验证宠物重量"""
        if value and value <= 0:
            raise serializers.ValidationError("重量必须为正数")
        return value
        
    def validate_height(self, value):
        """验证宠物高度"""
        if value and value <= 0:
            raise serializers.ValidationError("高度必须为正数")
        return value
        
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if instance.image:
            # 获取图片的相对路径
            image_path = instance.image.url
            # 确保只返回相对路径，不包含域名
            if image_path.startswith('http://') or image_path.startswith('https://'):
                # 分割URL，获取路径部分
                from urllib.parse import urlparse
                parsed_url = urlparse(image_path)
                image_path = parsed_url.path
            representation['image'] = image_path
        return representation